"""
---------------------------------------------------------------------
- File: service_roles.py
- Date: 2025/11/20
- Author: yangzhide
- Email: xxzjyzd@126.com
- Description: 相关用户业务逻辑
---------------------------------------------------------------------
"""

from sqlalchemy import func
from sqlalchemy.orm import selectinload
from sqlmodel import select, or_

from app.models.system import Roles
from app.schemas.system.roles import RoleCreate, RoleUpdate, RoleWithUser
from app.service.service_crud import CRUDBase


class ServiceRoles(CRUDBase[Roles, RoleCreate, RoleUpdate]):
    """
    角色业务逻辑
    """

    async def get_multi(self, *, skip: int = 0, limit: int = 10, filter_value: str = "") -> list[Roles] | None:
        """
        获取角色列表
        """

        # 1 基础查询
        condition = []

        # 2. 动态添加模糊查询
        if filter_value.strip():
            condition.append(
                or_(
                    self.model.role_name.like(f"%{filter_value}%"),
                    self.model.role_no.like(f"%{filter_value}%"),
                )
            )
        # 3. 计算总数
        count_query = select(func.count()).select_from(self.model).where(*condition)
        total = (await self.session.exec(count_query)).one()

        # 4. 分页查询, id排序
        query = select(self.model).where(*condition).order_by(self.model.id).offset(skip).limit(limit)
        result = (await self.session.exec(query)).all()
        return total, result  # type: ignore

    async def get_multiWithUser(self, *, skip: int = 0, limit: int = 10) -> list[RoleWithUser] | None:
        """
        获取角色列表（含有用户信息）
        """
        statement = (
            select(self.model)
            .options(selectinload(self.model.users))
            .order_by(self.model.id.desc())
            .offset(skip)
            .limit(limit)
        )
        result = await self.session.exec(statement)
        return result.all()  # type: ignore
